package com.zwh.se.common.audio;

import javax.sound.sampled.*;
import java.io.File;

/**
 * @author zwh
 * 音频系统
 */
public class AudioDemo2 {
    public static void main(String[] args) throws Exception {
//        String filePath = "audio";
//        ClassLoader classLoader = AudioDemo2.class.getClassLoader();
//        URL resourceURL = AudioDemo2.class.getClassLoader().getResource(filePath);
//        String path = resourceURL.getPath();
//        System.out.println(path);
        String path = "D:\\软件\\逆向\\ces\\audio";
        File file = new File(path);
        System.out.println(file.isDirectory());//是否为目录
        String[] list = file.list();//获得目录下的所有文件名
//        System.out.println(Arrays.toString(list));
        for (String s : list) {
            AudioPlay(path+"/"+s,1);
        }
    }

    /**
     * 播放音频文件
     * @param path 音频文件路径
     * @param sum 播放次数
     */
    static void AudioPlay(String path, Integer sum){
        File file = new File(path);
        if (file.isDirectory()){
            return;
        }
        byte[] buffer = new byte[1024 * 1024 * 15];
        try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
        ) {
            AudioFormat audioFormat = audioInputStream.getFormat();
            DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
            try (SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo)) {
                for (int i = 1; i <= sum; i++) {
                    System.out.println("现在播放"+ file.getName() +"第" + i + "遍");
                    int len = 0;
                    sourceDataLine.open(audioFormat, 1024 * 1024 * 15);
                    sourceDataLine.start();
                    audioInputStream.mark((int) path.length());

                    while ((len = audioInputStream.read(buffer)) > 0) {
                        sourceDataLine.write(buffer, 0, len);
                    }
//                    audioInputStream.reset();
                    sourceDataLine.drain();
                    sourceDataLine.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
